<?php

class FormAction extends BaseAction {
	
	private $excel_fileName = "formdata.xls";
	
	public function save() {
		if (! empty ( $_POST )) {
			
			$fid = ( int ) $_POST ['form_id'];
			$sid = (int) $_POST['sort_id'];
			$m_form = D ( "Form" );
			$fm = $m_form->where ( "id={$fid}" )->find ();
			if (! empty ( $fm )) {
				
				if ($_SESSION ['verify'] != md5 ( $_POST ['vcode'] )) {
					$this->error ( '验证码错误！' );
				}
				
				$fields = unserialize ( $fm ['content'] );
				$formData = array ();
				$formData2 = array ();
				$sText = '';
				for($i = 0; $i < count ( $fields ); $i ++) {
					$fen = $fields [$i] ['fen'];
					
					if (is_array ( $_POST [$fen] ))
						$val = join ( ",", $_POST [$fen] );
					else
						$val = $_POST [$fen];
					$formData [$fen] = $val;
					$fch_name = $fields[$i]['fname'];
					$formData2[$fch_name] = $val;
					$sText .= '<br />'.$fch_name.'：'.$val;
				}
				
				$sText .= '<hr />本邮件来自广基瑞特房地产网站系统，请勿直接回复！';
				$data ['form_id'] = $fid;
				$data ['content'] = serialize ( $formData );
				$m_formData = D ( "FormData" );
				$rt = $m_formData->add ( $data );
				if ($rt !== false) {
					
					//得到Email
					$m_sort = D('Sort');
					$sort = $m_sort->where('id='.$sid)->find();
					if( !empty($sort) && !empty($sort['email'])) {
						$email = $sort['email'];
						//发送E-mail通知
						import ( "@.Util.Mail" );								
						//生成excel文件
						//$this->_buildExcel ('标题',$formData2);					
						
						Mail::sendMail ( $email, $fm ['title'], $sText, '' );
					}
					$this->success ( "您提交的表单已保存成功！" );
				} else {
					$this->error ( "保存失败！" );
				}
			}
		}
	}
	
	/**
	 * 验证码
	 */
	public function vcode() {
		$type = isset ( $_GET ['type'] ) ? $_GET ['type'] : 'gif';
		
		import ( "ORG.Util.Image" );
		
		Image::buildImageVerify ( 4, 1, $type );
	
	}
	
	private function _buildExcel($form_title,$form_data) {
		vendor ( "PHPExcel.PHPExcel" );
		//创建Excell对象
		$objPHPExcel = new PHPExcel ();
		$objWriter = new PHPExcel_Writer_Excel5( $objPHPExcel );
		
		//设置当前的sheet
		$objPHPExcel->setActiveSheetIndex ( 0 );
		//设置sheet的name
		$objPHPExcel->getActiveSheet()->setTitle ($form_title);
		
		$i = 0;
		foreach ($form_data as $k=>$v)		
		{
			$cell = chr(65+$i++);
			//填充表头
			$objPHPExcel->getActiveSheet()->setCellValue($cell.'1',$k);
			//填充数据 
			$objPHPExcel->getActiveSheet()->setCellValue($cell.'2',$v);
		}
		//保存Excel文件
		$objWriter->save ( TEMP_PATH . $this->excel_fileName );
	
	}

}

?>